package com.mdx.rest.base;
import com.mdx.api.util.ResultVo;
import com.mdx.tools.util.ServletUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author : jiagang
 * @date : Created in 2021/7/23 15:55
 */
public class BaseController {

    private static Logger log = LogManager.getLogger(BaseController.class.getName());

    /**
     * 获取request
     */
    public HttpServletRequest getRequest() {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse() {
        return ServletUtils.getResponse();
    }

    /**
     * 获取session
     */
    public HttpSession getSession() {
        return getRequest().getSession();
    }


    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected ResultVo toAjax(int rows) {
        return rows > 0 ? ResultVo.success() : ResultVo.error();
    }


    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected ResultVo toAjax(boolean result) {
        return result ? ResultVo.success() : ResultVo.error();
    }

    /**
     * 返回成功消息
     */
    public ResultVo success(String message) {
        return ResultVo.success(message);
    }

    /**
     * 返回成功消息
     */
    public ResultVo success(String message, Object data) {
        return ResultVo.success(message,data);
    }

    /**
     * 返回成功消息
     */
    public ResultVo success(Object obj) {
        return ResultVo.success(obj);
    }

    /**
     * 返回失败消息
     */
    public ResultVo error(String message) {
        return ResultVo.error(message);
    }

    /**
     * 获取登录信息
     */
    public String getUserId(){
        String userDetails = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails){
            userDetails = ((UserDetails) principal).getUsername();
        }else {
            userDetails = principal.toString();
        }
        return userDetails;
    }
}
